package com.itqf.dao.impl;

import com.itqf.dao.OrderDao;
import com.itqf.entity.*;
import com.itqf.utils.DbUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;

import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class OrderDaoImpl implements OrderDao {

    private static QueryRunner queryRunner = new QueryRunner();

    @Override
    public void insertOrders(Orders orders) throws SQLException {
        String sql = "insert into orders (o_id,a_id,u_id,o_count,o_state,o_time) " +
                "value(?,?,?,?,?,?);";
        Object[] obj = {orders.getOid(), orders.getAid(), orders.getUid(), orders.getOcount()
                , orders.getOstate(), orders.getOtime()};
        queryRunner.update(DbUtils.getConnection(), sql, obj);
    }

    @Override
    public void insertItems(List<Item> items) throws SQLException {

        Object[][] params = new Object[items.size()][];
        String sql = "insert into item(o_id,p_id,i_count,i_num) value(?,?,?,?);";

        for (int i = 0; i < items.size(); i++) {
            Item item = items.get(i);
            params[i] = new Object[]{item.getOid(), item.getPid(), item.getIcount(), item.getInum()};
        }

        queryRunner.batch(DbUtils.getConnection(), sql, params);
    }

    @Override
    public List<Orders> selectOrderByUid(int uid) throws InvocationTargetException, IllegalAccessException, SQLException {

        String sql = "select o.o_id as oid,o.u_id as uid,o.a_id as aid," +
                "o.o_count as ocount,o.o_time as otime,o.o_state as ostate," +
                "a.a_name as aname,a.a_phone as aphone,a.a_detail as adetail, " +
                "a.a_state as astate from address a join orders o on a.a_id = o.a_id " +
                "where o.u_id = ?;";

        List<Map<String, Object>> list = queryRunner.query(DbUtils.getConnection(), sql, new MapListHandler(), uid);

        if (list == null) {
            return null;
        }

        List<Orders> ordersList = new ArrayList<>();
        for (Map<String, Object> map : list) {
            Orders orders = new Orders();
            Address address = new Address();

            BeanUtils.populate(orders, map);
            BeanUtils.populate(address, map);
            orders.setAddress(address);
            ordersList.add(orders);
        }

        return ordersList;
    }

    @Override
    public Orders selectOrderByOid(String oid) throws InvocationTargetException, IllegalAccessException, SQLException {

        String sql = "select o.o_id as oid,o.u_id as uid,o.a_id as aid," +
                "o.o_count as ocount,o.o_time as otime,o.o_state as ostate," +
                "a.a_name as aname,a.a_phone as aphone,a.a_detail as adetail, " +
                "a.a_state as astate from address a join orders o on a.a_id = o.a_id " +
                "where o.o_id = ?;";

        Map<String, Object> list = queryRunner.query(DbUtils.getConnection(), sql, new MapHandler(), oid);

        if (list == null) {
            //查询到的结果集为空
            return null ;
        }
        //映射对象信息
        Address address = new Address();
        Orders orders = new Orders();

        BeanUtils.populate(address,list);
        BeanUtils.populate(orders,list);

        orders.setAddress(address);
        return orders;
    }

    @Override
    public List<Item> selectItemsByOid(String oid) throws InvocationTargetException, IllegalAccessException, SQLException {
        //订单项和商品
        String sql = "select p.p_id as pid, p.t_id as tid,p.p_name as pname,p.p_time as ptime ," +
                "p.p_image as pimage,p.p_state as pstate ,p.p_info as pinfo ,p.p_price as pprice," +
                "i.o_id as oid, i.i_id as iid ,i.i_count as icount,i.i_num as inum " +
                "from product p join item i on p.p_id = i.p_id  where i.o_id = ?;";

        List<Map<String, Object>> list = queryRunner.query(DbUtils.getConnection(),sql, new MapListHandler(), oid);

        if (list == null) {
            return null;
        }

        List<Item> items = new ArrayList<>();

        for (Map<String, Object> map : list) {
            Item item= new Item();
            Product product = new Product();
            BeanUtils.populate(product, map);
            BeanUtils.populate(item, map);
            item.setProduct(product);
            items.add(item);
        }
        return items;
    }

    @Override
    public void updateStateByOid(String oid) throws SQLException {
        String sql = "update orders set o_state = ? where o_id = ?;";

        queryRunner.update(DbUtils.getConnection(),sql,2,oid);
    }

    @Override
    public List<Orders> findAllOrders() throws SQLException, InvocationTargetException, IllegalAccessException {
        String sql = "select o.o_id as oid,o.u_id as uid,o.a_id as aid ,\n" +
                "o.o_count as ocount,o.o_time as otime,o.o_state as ostate,\n" +
                "u.u_name as username\n" +
                "from `user` u join orders o on  o.u_id = u.u_id;";

        List<Map<String, Object>> list = queryRunner.query(DbUtils.getConnection(), sql, new MapListHandler());

        if (list == null) {
            return null;
        }

        List<Orders> ordersList = new ArrayList<>();

        for (Map<String, Object> map : list) {
            User user = new User();
            Orders orders = new Orders();
            //将集合中用户模块相关的数据映射到用户实体类对象里
            BeanUtils.populate(user, map);
            //将集合中订单模块相关的数据映射到订单实体类对象里
            BeanUtils.populate(orders,map);
            //将映射好的用户对象存入订单对象中
            orders.setUser(user);
            //将映射好数据的对象，存入集合中
            ordersList.add(orders);
        }
        return ordersList;
    }

    @Override
    public void changeStateByOid(String oid) throws SQLException {
        String sql = "update orders set o_state = ? where o_id = ?;";

        queryRunner.update(DbUtils.getConnection(),sql,3,oid);
    }

    @Override
    public  List<Orders> selectOrderByOidAndOstate(int uid, String ostate) throws SQLException, InvocationTargetException, IllegalAccessException {
        String sql = "select o.o_id as oid,o.u_id as uid,o.a_id as aid ,\n" +
                "o.o_count as ocount,o.o_time as otime,o.o_state as ostate\n" +
                "from orders o \n" +
                "where u_id = ? and o_state = ? ;";

        List<Orders> ordersList = queryRunner.query(DbUtils.getConnection(), sql, new BeanListHandler<Orders>(Orders.class), uid, ostate);

        return ordersList ;
    }
}
